package com.ruoyi.web.controller.system;

import com.axzhengxin.platform.common.enums.RedisKey;
import com.axzhengxin.platform.common.util.SmsSendService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.UserTokenHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Slf4j
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService sysUserService;


    private String REDIS_KEY = "TOKEN_REDIS_KEY:";

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 登录方法，适用于金融机构和政府用户在平台登录时，后台向企业征信中心注册登录状态并获取token
     *
     * @param username 登录信息，只需要用户名密码
     * @param md5Url
     * @return 登录结果
     */
    @PostMapping("/loginWithoutCaptcha/{username}/{md5Url}")
    public AjaxResult loginWithoutCaptcha(@PathVariable("username") String username, @PathVariable("md5Url") String md5Url) {
        AjaxResult ajax = AjaxResult.success();
        SysUser sysUser = sysUserService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            log.info("登录用户：{} 不存在.", username);
            return AjaxResult.error("登录用户：" + username + " 不存在");
        } else if (UserStatus.DELETED.getCode().equals(sysUser.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            return AjaxResult.error("对不起，您的账号：" + username + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(sysUser.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            return AjaxResult.error("对不起，您的账号：" + username + " 已停用");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String format = simpleDateFormat.format(new Date());
        log.info("---------------------------窗口调用免登录---------------------------");
        String md5 = Md5Utils.hash(username + format);
        log.info("-------------------md5:" + md5);
        if (!md5.equalsIgnoreCase(md5Url)) {
            return AjaxResult.error("对不起，加密过程出现未知问题！");
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(sysUser);
        loginUser.setExpireTime(30L);
        loginUser.setLoginTime(System.currentTimeMillis());
        Set<String> menuPermission = permissionService.getMenuPermission(sysUser);
        loginUser.setPermissions(menuPermission);
        String token = tokenService.createToken(loginUser);
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 一次性获取token
     *
     * @param
     * @return
     */
    @PostMapping("/getEncryptValue/{encryptValue}")
    public AjaxResult getTokenFromRedis(@PathVariable("encryptValue") String encryptValue) {
        String cacheToken = redisCache.getCacheObject(REDIS_KEY + encryptValue);
        try {
            redisCache.deleteObject(REDIS_KEY + encryptValue);
        } catch (Exception e) {
            log.info("——————————删除一次性token失败——————————");
            return AjaxResult.error("登录失败");
        }
        return AjaxResult.success(cacheToken);
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }


}
